/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.configuration;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.properties.ElsfsSecurityProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 设置 issuer
 *
 * @author zeng
 */
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(ElsfsSecurityProperties.class)
@Slf4j
public class IssuerConfiguration {

  private final Environment environment;
  private final ElsfsSecurityProperties elsfsSecurityProperties;

  @Bean("issuer")
  String issuer() {
    String issuer = elsfsSecurityProperties.getIssuer();
    if (issuer == null) {
      issuer = environment.getProperty("spring.security.oauth2.authorizationserver.issuer");
    }
    if (issuer == null) {
      issuer = environment.getProperty("spring.security.oauth2.resourceserver.jwt.issuer-uri");
    }
    if (issuer == null) {
      LOGGER.error(
          "issuer 未配置，配置优先级为：elsfs.security.issuer。"
              + "spring.security.oauth2.authorizationserver.issuer。"
              + "spring.security.oauth2.resourceserver.jwt.issuer-uri"
              + "配置默认的：\"https://www.elsfs.org\"");
      issuer = "https://www.elsfs.org";
    }

    return issuer;
  }
}
